package com.djp.smartapp.util;

import org.json.JSONObject;

import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class OkHttpUtil {
    public static final String HEAD_URL = "http://10.1.58.220:8081/dataInterface/";
    private OkHttpClient client;
    private MediaType type;
    private String res;

    //使用单例模式
    private OkHttpUtil() {
        //设置type为x-www-form-urlencoded模式
        client = new OkHttpClient();
        type = MediaType.parse("application/x-www-form-urlencoded");
    }
    private static OkHttpUtil okHttpUtil;
    public static OkHttpUtil getOkHttpUtil() {
        if (okHttpUtil == null) okHttpUtil = new OkHttpUtil();
        return okHttpUtil;
    }

    /**
     * 发送一条带参数的http网络请求，必须在线程中调用
     * @param url 请求头部为HEAD_URL参数，只需传入后面的部分
     * @param body 请求体，为"param1=xxx&param2=xxx" 格式
     * @return 以String形式返回传回的json数据
     */
    public String getPostRes(String url,String body){
        //构建RequestBody请求体
        RequestBody requestBody = RequestBody.create(type, body);

        //构建一个请求，使用post模式
        Request request = new Request.Builder()
                .post(requestBody)
                .url(HEAD_URL + url)
                .build();

        //发送请求，在没报错的情况下返回传回的string数据
        try {
            Response response = client.newCall(request).execute();
            res = response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return res;
    }

    public String getPostRes(String url){
        RequestBody requestBody = RequestBody.create(type, "");
        Request request = new Request.Builder()
                .post(requestBody)
                .url(HEAD_URL + url)
                .build();

        try {
            Response response = client.newCall(request).execute();
            res = response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return res;
    }
}
